package com.lobo.blog.aspect;

import com.lobo.blog.log.RequestLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @authoer:MacieSerenity
 * @createDate: 2022/9/27
 * @description: 通过切面将controller对象执行的过程打印到日志当中
 */
@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 将controller的所有方法都记录到日志
     */
    @Pointcut("execution( * com.lobo.blog.controller.*.*(..)) && (@annotation(org.springframework.web.bind.annotation.RequestMapping))")
    public void log() {
    }

    @Pointcut("execution( * com.lobo.blog.controller.admin.*.*(..)) && (@annotation(org.springframework.web.bind.annotation.RequestMapping))")
    public void AdminOperationLog() {
    }


    @Before(value = "log() || AdminOperationLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attribute = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attribute.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("Request:{}" + requestLog);
    }

    @After(value = "log()|| AdminOperationLog()")
    public void doAfter() {
    }

    /**
     * 捕获返回参数
     *
     * @param result 返回的参数
     */
    @AfterReturning(pointcut = "log()|| AdminOperationLog()", returning = "result")
    public void doAfterReturn(Object result) {
        logger.info("Return:Result == " + result);
    }

}
